/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */

/*
// 开放的接口
import http from './interface'

http.config.baseUrl = "http://localhost:8080/api/"

http.request(url:'user/list',method:'GET').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list', {status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.post('user', {id:1, status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.put('user/1', {status: 2}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.delete('user/1').then((res)=>{
	console.log(JSON.stringify(res))
}) 

*/
import {isEmpty} from '@/common/graceChecker.js'
import {hostRoot} from '@/common/util.js'
import _GENV from '@/common/env.js'
export default {
	config: {
		baseUrl: process.env.NODE_ENV === 'development'?_GENV.GApi:hostRoot,
		header: {
			'Content-Type':'application/json;charset=UTF-8',
			'Content-Type':'application/x-www-form-urlencoded'
		},  
		data: {},
		method: "POST",
		dataType: "json",  /* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		retry: 3, // 最大请求次数
		timeout: 2 * 1000, // 请求超时时间
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.data = options.data || {}
		options.method = options.method || this.config.method
		if(options.url.indexOf(options.baseUrl) === -1 ){	// 请求路径中不包含根目录的时候 添加根目录
			options.url = options.baseUrl + options.url
		}
		
		//TODO 数据签名
		/* 
		_token = {'token': getStorage(STOREKEY_LOGIN).token || 'undefined'},
		_sign = {'sign': sign(JSON.stringify(options.data))}
		options.header = Object.assign({}, options.header, _token,_sign) 
		*/
	   
		return new Promise((resolve, reject) => {
			let _config = null
			
			options.complete = (response) => {
				let statusCode = response.statusCode
				response.config = _config
				
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				if (statusCode === 200) { //成功
					let res = response.data  
					 if(isEmpty(res)){
						// uni.showToast({
						//     icon: 'none',
						//     title: '服务器故障！'
						// }); 
						return;
					 }
					if(res.ret != 200){
						uni.showToast({
						    icon: 'none',
						    title: res.msg
						});
					}else{
						resolve(res.data);
					}
				} else {	// 连接失败
					
					// 如果连接失败会再次请求，直到超过最多请求次数
					let config = response.config
					//console.log(config)
					// If config does not exist or the retry option is not set, reject
					if (!config || !config.retry) return reject(response)
					
					 // 设置请求次数
					config.__retryCount = config.__retryCount || 0
				
					// 是否超过最大请求次数
					if (config.__retryCount >= config.retry) {
					  // 报错
					  console.log('错误：' + response.errMsg)// for debug
					  // uni.showToast({
					  //     icon: 'none',
					  //     title: '网络故障！'
					  // });
					  return reject(response)
					}
				
					// 请求次数自增
					config.__retryCount += 1
					console.log('再次请求：' + config.__retryCount)
					
					// 设置定时器 超过请求时间后重新请求
					setTimeout(()=>{
						this.request(config).then(res=>{
							resolve(res);
						})
					}, config.timeout || 1)
					
				}
			}

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			

			uni.request(_config);
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'  
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}


